package team.nmsg.photo;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import team.nmsg.ge.system.util.ServerParams;
import team.nmsg.photo.bean.ProjectBean;

public class PhotoUtil {
	
	private static Logger log = LoggerFactory.getLogger(PhotoUtil.class);
	
	public final static String sep = "/";
	
	public static final String res = "resources";
	
	
	
	public static Map<String, String> resToPath = new HashMap<>();
	public static void initDir() {
		
		try {
			Properties pros = ServerParams.pros;
			
			Set<Entry<Object, Object>> entrySet = ServerParams.pros.entrySet();
			for (Entry<Object, Object> en : entrySet) {
				String key = en.getKey().toString();
				String value = en.getValue().toString();
				if (key.startsWith("HISTORY_RES_DIR")) {
					String[] split = value.split("#");
					resToPath.put( split[0] , split[1] );
				}
			}
			
			String curDir = pros.getProperty("CURRENT_SAVE_PATH");
			String curRes = pros.getProperty("CURRENT_ACCESS_RES");
			if( curDir!=null  &&  curRes!= null) {
				File file = new File(curDir);
				if( !file.exists() ) {
					file.mkdirs();
				}
				
				baseDir = curDir;
				tmpdir = baseDir + "/tmp";
				prodir = baseDir + proDirName;
				userProPath = curRes + proDirName;
				
				resToPath.put(curRes + sep  , curDir  + sep );
			}
		} catch (Exception e) {
			log.error( "" , e);
		}
		
	}
	
	public static String proDirName = "/pro";
	public static String picDirName = "/imgs";
	
	public static String userDir = System.getProperty("user.dir").replace("\\", sep);
	public static String defaultProDir = userDir + "/resources/pro";
	
	public static String baseDir = System.getProperty("user.dir").replace("\\", sep);
	public static String tmpdir = baseDir + "/resources/tmp";
	public static String prodir = baseDir + "/resources/pro";
	public static String userProPath = "/resources/pro";
	
	public static final long SIZE_100KB = 100l * 1024 *8 ;
	
	
	public static final int  pro_status_init = 0;
	public static final int  pro_status_start = 1;
	public static final int  pro_status_end = 2;
	
	public static String pro_type_default="0";  //默认
	public static String pro_type_pet="1";//宠物
	public static String pro_type_meeting ="2";//会议
	public static String pro_type_train="3";//培训
	public static String pro_type_show ="4";//演出
	public static String pro_type_music ="5";//音乐节
	public static String pro_type_sport ="6";//运动
	public static String pro_type_exhibition="7";//展会
	
	public static final int  pro_show = 0;
	public static final int  pro_notshow = 1;
	
	
	public static String imgtype_cover = "coverImg";
	public static String imgtype_share = "shareIconImg";
	public static String imgtype_ad = "advertiseImg";
	
	public static final int  THUMB_W = 500;
	public static final int  THUMB_H = 350;

	public static final String THUMB_FLAG = "_thumb";
	public static final String DOT_JPG = ".jpg";
	
	public static String getProjectDir( ProjectBean pro ) {
		
		String proSaveDir = getProSaveDir(pro);
		String baseDir = proSaveDir +PhotoUtil.sep +"a"+pro.getProjectId();
		return baseDir;
	}
	
	public static String getImgsDir( ProjectBean pro ) {
		
		String proSaveDir = getProSaveDir(pro);
		String aaa = proSaveDir + PhotoUtil.sep+"a"+pro.getProjectId()  +PhotoUtil.picDirName ;
		return aaa;
	}
	
	private static String getProSaveDir(  ProjectBean pro  ) {
		String prifix = defaultProDir;
		String imgBaseDir = pro.getImgBaseDir();
		if( imgBaseDir == null ) {
			return prodir;
		}
		if( imgBaseDir.startsWith(sep + res) ) {
			prifix = defaultProDir;
		}else {
			String key = imgBaseDir.substring( 0 , imgBaseDir.indexOf( "pro" ) );
			String baseDir = resToPath.get(key);
			if( baseDir!=null ) {
				return baseDir + "pro";
			}
		}
		return prifix;
	}
	
	public static String getImgsRDir( ProjectBean pro ) {
		
		String aaa = pro.getImgBaseDir()  +PhotoUtil.picDirName ;
		return aaa;
	}
	
	
	public static String formatDate(Long timestamp){
		
		if( timestamp ==null ){
			return "";
		}
		
		Date date = new Date(timestamp);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//2019-07-10 22:01:00
		return sdf.format(date);
	}
	
	public static Long parseStrDate(String  source ) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date parse = sdf.parse(source);
		return parse.getTime();
	}
	
	public static String getSuffixWithDot(String pathOrName ) {
		return pathOrName.substring(pathOrName.lastIndexOf("."));
	}
	
	   /**
     * 指定图片宽度和高度和压缩比例对图片进行压缩
     * 
     * @param imgsrc
     *            源图片地址
     * @param imgdist
     *            目标图片地址
     * @param widthdist
     *            压缩后图片的宽度
     * @param heightdist
     *            压缩后图片的高度
     * @param rate
     *            压缩的比例
     */
    public static void reduceImg(String imgsrc, String imgdst, int widthdist, int heightdist, Float rate) {
        try {
            File srcfile = new File(imgsrc);
            // 检查图片文件是否存在
            if (!srcfile.exists()) {
                System.out.println("文件不存在");
            }
            // 如果比例不为空则说明是按比例压缩
            if (rate != null && rate > 0) {
                //获得源图片的宽高存入数组中
                int[] results = getImgWidthHeight(srcfile);
                if (results == null || results[0] == 0 || results[1] == 0) {
                    return;
                } else {
                    //按比例缩放或扩大图片大小，将浮点型转为整型
                    widthdist = (int) (results[0] * rate);
                    heightdist = (int) (results[1] * rate);
                }
            }
            // 开始读取文件并进行压缩
            Image src = ImageIO.read(srcfile);

            // 构造一个类型为预定义图像类型之一的 BufferedImage
            BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);

            //绘制图像  getScaledInstance表示创建此图像的缩放版本，返回一个新的缩放版本Image,按指定的width,height呈现图像
            //Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
            tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);

            //创建文件输出流
            FileOutputStream out = new FileOutputStream(imgdst);
            //将图片按JPEG压缩，保存到out中
            ImageIO.write(tag, "jpg", out);
            //关闭文件输出流
            out.close();
        } catch (Exception e) {
        	log.error( "" , e );
        }
    }
    
	public static void cutAndReduceImage2( String srcFile , String newFile   ) throws Exception {
		
		double m1 = (double)THUMB_W / (double)THUMB_H;
		
		ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(srcFile));
		@SuppressWarnings("rawtypes")
		Iterator it = ImageIO.getImageReaders(iis);
		ImageReader imagereader = (ImageReader) it.next();
		imagereader.setInput(iis);
		
		int srcWidth = imagereader.getWidth(0);
		int srcHeight = imagereader.getHeight(0);
		double m2 = (double)srcWidth / (double)srcHeight;
		
		int x1 = 0;
		int y1 = 0;
		
		int w1 = 0;
		int h1 = 0;
		if( m1>m2  ) {
			w1 = srcWidth;
			h1 = (int) (srcWidth/m1);
			
			x1 =0 ;
			y1 = (srcHeight-h1) / 2;
		}else {
			h1 = srcHeight;
			w1 = (int) (srcHeight * m1);
			
			y1 = 0;
			x1 =  (srcWidth-w1) / 2;
			
		}
		

		
		ImageReadParam par = imagereader.getDefaultReadParam();
		par.setSourceRegion(new Rectangle(x1, y1, w1, h1));
		BufferedImage cutBi = imagereader.read(0, par);
		
		int widthdist = THUMB_W;
		int heightdist = THUMB_H;
		BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(cutBi.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
		
		String suffix = getSuffixWithDot(newFile).substring(1 );
		ImageIO.write( tag ,  suffix , new File(newFile) );
		iis.close();
		
	}
    
//	public static void cutImage( String srcFile , String newFile, int x, int y, int w, int h ) throws Exception {
//		
//		ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(srcFile));
//		@SuppressWarnings("rawtypes")
//		Iterator it = ImageIO.getImageReaders(iis);
//		ImageReader imagereader = (ImageReader) it.next();
//		imagereader.setInput(iis);
//		ImageReadParam par = imagereader.getDefaultReadParam();
//		par.setSourceRegion(new Rectangle(x, y, w, h));
//		BufferedImage bi = imagereader.read(0, par);
//		String suffix = getSuffixWithDot(newFile).substring(1 );
//		ImageIO.write(bi,  suffix , new File(newFile) );
//		iis.close();
//		
//	}
	
	public static void cutAndReduceImage( String srcFile , String newFile, int x, int y, int w, int h   ) throws Exception {
		
		ImageInputStream iis = ImageIO.createImageInputStream(new FileInputStream(srcFile));
		@SuppressWarnings("rawtypes")
		Iterator it = ImageIO.getImageReaders(iis);
		ImageReader imagereader = (ImageReader) it.next();
		imagereader.setInput(iis);
		ImageReadParam par = imagereader.getDefaultReadParam();
		par.setSourceRegion(new Rectangle(x, y, w, h));
		BufferedImage cutBi = imagereader.read(0, par);
		
		int widthdist = THUMB_W;
        int heightdist = THUMB_H;
        BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);
        tag.getGraphics().drawImage(cutBi.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
		
		String suffix = getSuffixWithDot(newFile).substring(1 );
		ImageIO.write( tag ,  suffix , new File(newFile) );
		iis.close();
		
	}
	
	public static int[] getCutXYWH( int srcW , int srcH  ) {
		int[] res = new int[4];

		int w = 0;
		int h = 0;
		if( srcW<srcH  ) {
			w = srcW;
			h = srcW;
		}else {
			w = srcH;
			h = srcH;
		}
		
		res[0] = (srcW - w)/2;  // x 
		res[1] = (srcH - h)/2;  // y 
		res[2] = w;      // w
		res[3] = h;   //h
		return res;
	}
	
	public static int[] getSquareBySrc(int srcW , int srcH ) {
		int[] res = new int[2];
		if( srcW<srcH  ) {
			res[0] =srcW;
			res[1] =srcW;
		}else {
			res[0] =srcH;
			res[1] =srcH;
		}
		return res;
	}


    /**
     * 获取图片宽度和高度
     * 
     * @param 图片路径
     * @return 返回图片的宽度
     */
    public static int[] getImgWidthHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int result[] = { 0, 0 };
        try {
            // 获得文件输入流
            is = new FileInputStream(file);
            // 从流里将图片写入缓冲图片区
            src = ImageIO.read(is);
            result[0] =src.getWidth(null); // 得到源图片宽
            result[1] =src.getHeight(null);// 得到源图片高
            is.close();  //关闭输入流
        } catch (Exception e) {
        	log.error( "" , e );
        }

        return result;
    }

}
